package club.yunzhi.springcourse.controller;

import club.yunzhi.springcourse.entity.Teacher;
import club.yunzhi.springcourse.repository.TeacherRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Optional;

/**
 * 教师
 */
@CrossOrigin(origins = "http://localhost:8080/")
@RestController
@RequestMapping("teacher")
public class TeacherController {
  private Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private TeacherRepository teacherRepository;

  /**
   * 张三、李四两个教师初始化
   */
  @PostConstruct
  public void initData() {
    logger.info("初始化教师信息");
    Teacher zhangsan = new Teacher();
    zhangsan.setName("张三");
    zhangsan.setSex(true);
    zhangsan.setEmail("zhangsan@codedemo.club");
    zhangsan.setUsername("zhangsan");
    zhangsan.setPassword("yunzhi.club");
    this.teacherRepository.save(zhangsan);

    Teacher lisi = new Teacher();
    lisi.setName("李四 ");
    lisi.setSex(false);
    lisi.setEmail("lisi@codedemo.club");
    lisi.setUsername("lisi");
    lisi.setPassword("club.yunzhi");
    this.teacherRepository.save(lisi);
  }

  @DeleteMapping("{id}")
  public void deleteById(@PathVariable Long id) {
    this.teacherRepository.deleteById(id);
  }

  @GetMapping
  public Iterable<Teacher> getAll() {
    ArrayList<Teacher> teachers = (ArrayList<Teacher>) this.teacherRepository.findAll();
    return teachers;
  }

  @GetMapping("{id}")
  public Teacher getById(@PathVariable Long id) {
    Optional<Teacher> teacher = this.teacherRepository.findById(id);
    if (teacher.isPresent()) {
      return teacher.get();
    } else {
      return null;
    }
  }

  @RequestMapping("login")
  public void login(HttpServletRequest request, HttpServletResponse response) {
    // 获取到header中的特定信息
    String auth = request.getHeader("Authorization");
    logger.info("获取到的认证header值为" + auth);
    if (auth != null) {
      // 进行转码，获取到用户名:密码
      String encodeAuth = auth.substring(6);
      logger.info("获取到的转码为" + encodeAuth);

      // 获取用户名、获取密码
      String usernameAndPassword = new String(Base64.getDecoder().decode(encodeAuth));
      logger.info("转码后的结果为" + usernameAndPassword);

      String[] usernameAndPasswordArray = usernameAndPassword.split(":");
      String username = usernameAndPasswordArray[0];
      String password = usernameAndPasswordArray[1];

      // 判断用户名密码是否正确
      Optional<Teacher> teacherOptional = this.teacherRepository.findByUsername(username);
      if (teacherOptional.isPresent()) {
        Teacher teacher = teacherOptional.get();
        if (teacher.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
          logger.info("用户认证成功，返回200（什么也不做）");
          return;
        }
      }
    }

    logger.info("未获取到header中的认证信息或认证信息有误，返回401");
    response.setStatus(401);
  }

  /**
   * 保存新教师
   *
   * @return 保存后的教师
   */
  @PostMapping
  public Teacher save(@RequestBody Teacher teacher) {
    this.teacherRepository.save(teacher);
    return teacher;
  }

  @PutMapping("/{id}")
  public Teacher updateById(@PathVariable Long id, @RequestBody Teacher newTeacher) {
    // 查询出ID 对应的教师
    Optional<Teacher> teacherOptional = this.teacherRepository.findById(id);
    if (teacherOptional.isPresent()) {
      // 更新该教师的各个属性
      Teacher teacher = teacherOptional.get();
      teacher.setName(newTeacher.getName());
      teacher.setUsername(newTeacher.getUsername());
      teacher.setEmail(newTeacher.getEmail());
      teacher.setSex(newTeacher.getSex());
      this.teacherRepository.save(teacher);
      return teacher;
    } else {
      return null;
    }
  }
}